'''
Created on Mar 11, 2011

@author: Jialai_Zhu
'''
import pymongo
class mongo_db():
    @staticmethod
    def start():
        import os
        dir=os.path.dirname(__file__)
        import  subprocess
        
        db_path=os.path.join(dir,'..\\data\\db\\')
        db_path=os.path.abspath(db_path)
        try:
            os.makedirs(db_path)
        except:
            pass
        _popen=subprocess.Popen(args='"%s"  --rest run --dbpath "%s"'%(os.path.join(dir,"mongod.exe"),db_path))
class mongo_query_base():         
    def __init__(self,table=None,db_name=None,table_name=None):
        if table==None and db_name==None:raise
        self.con = pymongo.Connection() 
        if table:
            self.c_db = self.con[table.db_name()]
            self.c_dt = self.c_db[table.table_name()]
        else:
            self.c_db = self.con[db_name]
            self.c_dt = self.c_db[table_name]
    def has(self,key):
        r=self.c_dt.find(key)
        for s in r:return True
        return False
    def find(self,key,limit=1):
        if limit==1:
            for i in self.c_dt.find(key):
                return i
            return None
        if limit==0:
            return self.c_dt.find(key)
        return self.c_dt.find(key).limit(limit)
    def count(self):
        return self.c_dt.count()
    def insert(self,key):
        try:
            self.c_dt.insert(key)
        except Exception,ex:
#            LOG.error(ex)
            print ex
    def update(self,key,value): 
        try:
            self.c_dt.update(key,{"$set":value})
        except Exception,ex:
             print ex
    def update_item(self,item,value): 
        try:
            self.update({'_id':item['_id']}, value)
        except Exception,ex:
             print ex      
class mongo_table_base():
    db=None
    def __init__(self):
        pass
    def db_name(self):
        return self._db_name
    def table_name(self):
        return self._table_name

    
if __name__ == "__main__":
    mongo_db.start()
        
